package cn.edu.ctbu.lab.service.impl;

import cn.edu.ctbu.lab.dao.ScoreRepository;
import cn.edu.ctbu.lab.domain.Score;
import cn.edu.ctbu.lab.vo.BTPageDO;
import cn.edu.ctbu.lab.vo.ScoreExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ScoreServiceImpl implements cn.edu.ctbu.lab.service.ScoreService {

    @Autowired
    private ScoreRepository scoreRepository;


    @Override
    public Optional<Score> findById(Integer id){

        Optional<Score> score=scoreRepository.findById(id);
        return score;
    }


    @Override
    public List<Score> findAll(){

        List<Score> myList=scoreRepository.findAll();
        return myList;
    }

    @Override
    public BTPageDO<ScoreExt> findByPage(Integer courseId,int pageIndex, int pageSize){

        /*Sort sort =  Sort.by(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
        Page<Score> myList=scoreRepository.findAll(pageable);*/
        BTPageDO<ScoreExt> pageDO=new BTPageDO<ScoreExt>();


        if(pageIndex<1){
            pageIndex=1;
        }

        Integer offset=(pageIndex-1)*pageSize;
        List<ScoreExt> scoreExts=scoreRepository.getByPage(courseId,offset,pageSize);
        Integer total=scoreRepository.getByPageCount();
        pageDO.setRows(scoreExts);
        pageDO.setTotal(total);

        return pageDO;

    }




    @Override
    public Score add(Score score){
        scoreRepository.save(score);
        return score;
    }

    @Override
    public Score update(Score score){

        scoreRepository.save(score);
        return score;
    }


    @Override
    public int delete(Score score){

        try{

            scoreRepository.delete(score);
        }catch (Exception e){

            //throw  e;
            return -1;
        }
        return 1;
    }

    @Override
    public  int delete(Integer id){
        Score score=scoreRepository.getOne(id);

        return delete(score);

    }


}
